/**
 * 指标明细页面，解析html代码的js
 */
/** 获取某年的某天是第几周 */
var getWeekNumber = function (dateStr) {
    var year = dateStr.substr(0, 4);
    var month = dateStr.substr(5, 2);
    var days = dateStr.substr(8, 2);
    year = parseInt(year);
    month = parseInt(month) - 1;
    days = parseInt(days);

    // 那一天是那一年中的第多少天
    var date1 = new Date(year, 0, 1);
    var date2 = new Date(year, month, days);
    var d1 = date1.getTime();
    var d2 = date2.getTime();
    var d = (d2 - d1) / 24 / 60 / 60 / 1000 + 1;
    // 那一年第一天是星期几
    var yearFirstDay = date1.getDay() || 7;
    d += yearFirstDay;
    var week = Math.ceil(d / 7) - 1;
    if (week < 1) {
        return getWeekNumber((year - 1) + "-12-31");// 如果周次小于1，说明是去年的最后一周，计算全年的12月31日
    } else
        return date2.getFullYear() + "W" + week;
};

var ConditionManager = (function () {
    var ins = {};
    this.addCondition = function (inst) {
        inst.removeClass("form-widget-control-wapper");
        var conditionId = "condition_" + new Date().getTime();
        ins[conditionId] = inst;
        return conditionId;
    };
    this.getCondition = function (conditionId) {
        return ins[conditionId];
    };
    this.setComplete = function (conditionId) {
        ins[conditionId].status = "complete";
    };
    this.setLoading = function (conditionId) {
        ins[conditionId].status = "loading";
    };
    this.getStatus = function () {
        var status = "complete";
        $.each(ins, function (i, item) {
            if (item.status == "loading") {
                status = "loading";
                return false;
            }
        });
        return status == "complete";
    };
    this.getParams = function () {
        var params = {};
        $.each(ins, function (i, item) {
            var p = item.getValue();
            params = $.extend(params, p);
        });
        return params;
    }

    return this;
})();

/**  PC端时间控件  */
$.fn.webDateCondition = function (action, param) {
    var _this = this;

    this.init = function (p) {
        var conditionId = ConditionManager.addCondition(_this);
        var defaultSjwd = p.defaultSjwd;
        var now = new Date();
        layDate(now,defaultSjwd);
        ConditionManager.setComplete(conditionId);
        return _this;
    };
    this.setValue = function (key, value) {
        _this.find("div[type=" + key + "]").find("input").val(value);
        return _this;
    }
    this.getValue = function () {
        var p = {};
        _this.find("div[type]").find("input").each(function (i, item) {
            var key = $(item).parents("div[type]").attr("type");
            var value = $(item).val();
            p[key] = value;
        });
        return p;
    }
    return this[action](param);
}

/** 日期组件 */
$.fn.dateCondition = function (action, params) {
    this.init = function () {
        var _this = this;
        var id = params.id, value = params.value, data_range = JSON.parse(params.date_range);
        var type = JSON.parse(params.date_range).TYPE;
        switch (type) {
            case "1":
                break;
            case "2":
                params = $.extend({}, params, {
                    value: getWeekNumber(params.value)
                });
                break;
            case "3":
                params = $.extend({}, params, {
                    value: params.value.substr(0, 7)
                });
                break;
            case "4":
                params = $.extend({}, params, {
                    value: params.value.substr(0, 4)
                });
                break;

            default:
                break;
        }

        return _this.setValue(params);
    }
    this.getValue = function () {
        var sv = $("#startDate").attr("value"), ev = $("#endDate").attr("value");
        var params = {};
        params["startDate"] = sv;
        params["endDate"] = ev;
        return params;
    }
    //传入sql中的时间参数没有-
    this.getSqlValue = function () {
        var p = this.getValue();
        p.startDate = p.startDate.replace(/-/g, '');
        p.endDate = p.endDate.replace(/-/g, '');
        return p;
    }
    this.setValue = function (params) {
        var id = params.id, value = params.value, data_range = JSON.parse(params.date_range);
        var obj = $("#" + id);
        obj.data("DATE_RANGE", data_range);
        if (!id || !value) {
            return $(this);
        }
        obj.attr("value", value).dateCondition("setShow", {
            sjwd: data_range.TYPE,
            value: value
        });
        $("#" + id + "_pick").dateCondition("setShow", {
            sjwd: data_range.TYPE,
            value: value
        });
        return $(this);
    }
    this.setShow = function (params) {
        var sjwd = params.sjwd + "", value = params.value;
        switch (sjwd) {
            case "1":// 日
                value = value.split("-");
                $(this).html("<span>" + value[0] + "</span>/<span>" + value[1] + "</span>/<span>" + value[2] + "</span>");
                break;
            case "2":// 周
                value = value.split("W");
                $(this).html("<span>" + value[0] + "</span>年<span>" + value[1] + "</span>周");
                break;
            case "3":// 月
                value = value.split("-");
                $(this).html("<span>" + value[0] + "</span>年<span>" + value[1] + "</span>月");
                break;
            case "4":// 年
                $(this).html("<span>" + value + "</span>年");
                break;
            default:
                break;
        }
        return $(this);
    }
    return this[action](params);
}

/** 下拉框组件 */
$.fn.select_common = function (action, contentData, contentDataAll) {
    var _this = this;
    var time = new Date().getTime();
    this.uid = time;
    this.contentData = contentData;
    this.getObj = function ()// 获取当前父级div对象
    {
        return $("#" + this.contentData["CONTROL_ID"]).parents(".form-widget-control-wapper");
    }
    var sele = this.getObj();
    if(!sele.hasClass("ft")){
        sele.addClass("ft");
        sele.find(".dropdown-menu.open").on("click", 'li a', function () {
            _this.click();
        })
    }
    this.click = function () {
        _this.choose(this);
    }
    this.getValue = function ()// 获取行政区划的值
    {
        var id = this.getObj().find("li.list").attr("id");
        var value = this.getObj().find("select.selectpicker").val();
        var params = {};
        params[id] = value;
        return params;
    }
    this.setValue = function (result)// 设置下拉框选项内容
    {
        var data = result.data;
        if (result.state == "true") {
            data = JSON.parse(data);
            var select = this.getObj().find("select.selectpicker");
            select.empty();
            if (this.contentData["DEFAULT"] == "true") {
                var option = $("<option>");
                option.attr("value", "").html("不限");
                select.append(option);
            }
            for (var i in data) {
                var option = $("<option>");
                option.attr("value", data[i].ID).html(data[i].NAME);
                select.append(option);
            }
            /** 刷新下拉框的值 */
            select.selectpicker('val', '');
            select.selectpicker('refresh');
            select.selectpicker({
                size: 6
            });
            var _this = this;
            _this.getObj().find(".list").attr("state", "complete");
            _this.find("li a").first().trigger("click");
            // if ($("#btn_submit").data("state") == "true") {
            //     $("#btn_submit").trigger("click");
            // }
        }
    }
    this.querySQL = function (params)// 查询sql设置下拉框内容
    {
        var _this = this;
        var sql = params.sql;
        delete params.sql;

        queryBySql(sql, function (result) {
            return _this.setValue(result);
        }, params);
    }
    this.choose = function (obj)// 改变下拉框的状态
    {
        var _this = this;
        var relation = this.contentData["RELATION"];
        /** 判断是否存在级联关系进行下个下拉框的赋值 */
        if (relation) {
            var ins = $("#" + relation).parents(".form-widget-control-wapper");
            var param = _this.getValue();
            var params = contentDataAll[ins.attr("id")];
            params = $.extend(params, {}, param);
            if("select_xzqh"==params.type)
            {
                ins.select_xzqh("loadData", params, contentDataAll);
            }
            else if("select_jg"==params.type)
            {
                ins.select_jg("loadData", params, contentDataAll);
            }
            else
            {
                ins.select_common("loadData", params, contentDataAll);
            }
        }
    }
    this.loadData = function (param)// 加载下拉框内容
    {
        var _this = this;
        var params = {};
        params = $.extend(params, param);
        params["sql"] = contentData["SQL"];
        this.querySQL(params);
        return _this;
    }
    return this[action](contentData);
}

$.fn.select_xzqh = function(action, contentData, contentDataAll) {
    var falg = false;
    var _this = this;
    this.contentData = contentData;
    this.getObj = function ()// 获取当前父级div对象
    {
        return $("#" + this.contentData["CONTROL_ID"]).parents(".form-widget-control-wapper");
    }
    var sele = this.getObj();
    if(!sele.hasClass("ft")){
        sele.addClass("ft");
        sele.find(".dropdown-menu.open").on("click", 'li a', function () {
            _this.click();
        })
    }
    this.click = function () {
        _this.choose(this);
    }
    this.getValue = function ()// 获取行政区划的值
    {
        var id = this.getObj().find("li.list").attr("id");
        var value = this.getObj().find("select.selectpicker").val();
        var params = {};
        params[id] = value;
        return params;
    }
    this.setValue = function (result)// 设置下拉框选项内容
    {
        var data = result.data;
        if (result.state == "true") {
            data = JSON.parse(data);
            var select = this.getObj().find("select.selectpicker");
            select.empty();
            if (this.contentData["DEFAULT"] == "true") {
                var option = $("<option>");
                option.attr("value", "").html("不限");
                select.append(option);
            }
            for (var i in data) {
                var option = $("<option>");
                option.attr("value", data[i].ID).html(data[i].NAME);
                select.append(option);
            }
            /** 刷新下拉框的值 */
            select.selectpicker('val', '');
            select.selectpicker('refresh');
            select.selectpicker({
                size: 6
            });
            var _this = this;
            _this.getObj().find(".list").attr("state", "complete");
            falg = true;
            _this.find("li a").first().trigger("click");
        }
    }
    this.querySQL = function (params)// 查询sql设置下拉框内容
    {
        var _this = this;
        var sql = params.sql;
        delete params.sql;

        queryBySql(sql, function (result) {
            return _this.setValue(result);
        }, params);
    }
    this.choose = function (obj)// 改变下拉框的状态
    {
        var _this = this;
        var relation = this.contentData["RELATION"];
        /** 判断是否在顶部显示 */
        if (this.contentData["IS_SHOW_TOP"] == "1") {
            var div = $("#chart_container").find(".page-search-top .place-div");
            div.html(text);
        }
        /** 判断是否存在级联关系进行下个下拉框的赋值 */
        if (relation) {
            var ins = $("#" + relation).parents(".form-widget-control-wapper");
            var param = _this.getValue();
            var params = contentDataAll[ins.attr("id")];
            params = $.extend(params, {}, param);
            if("select_xzqh"==params.type)
            {
                ins.select_xzqh("loadData", params, contentDataAll);
            }
            else if("select_jg"==params.type)
            {
                ins.select_jg("loadData", params, contentDataAll);
            }
            else
            {
                ins.select_common("loadData", params, contentDataAll);
            }
        }
    }
    this.loadData = function (param)// 加载下拉框内容
    {
        falg = false;
        var _this = this;
        var params = {};
        var control_id = this.contentData["CONTROL_ID"];
        params = $.extend(params, param);
        params["sql"] = contentData["SQL"];
        var res = {
            state: "true",
            data: JSON.stringify([{
                ID: userInfo[control_id],
                NAME: userInfo[control_id.substring(0, control_id.length - 2) + "MC"]
            }])
        };
        // var ssqxdm = userInfo[control_id];
        // if (control_id == "PRODM") {
        //     _this.contentData.DEFAULT = "false";
        //     this.setValue(res);
        // } else
        if (control_id == "JGXZQHDM") {
            if (ssqxdm.substr(2, 6) == "0000") {
                this.querySQL(params);
            } else {
                _this.contentData.DEFAULT = "false";
                this.setValue(res);
            }
        }
        // else if (control_id == "SSQXDM")
        // {
        //     if (ssqxdm.substr(4, 6) == "00") {
        //         this.querySQL(params);
        //     } else {
        //         _this.contentData.DEFAULT = "false";
        //         this.setValue(res);
        //     }
        // }
        return falg;
    }
    return this[action](contentData);
}

$.fn.select_jg = function(action, contentData, contentDataAll) {
    var _this = this;
    this.contentData = contentData;
    this.getObj = function ()// 获取当前父级div对象
    {
        return $("#" + this.contentData["CONTROL_ID"]).parents(".form-widget-control-wapper");
    }
    var sele = this.getObj();
    if(!sele.hasClass("ft")){
        sele.addClass("ft");
        sele.find(".dropdown-menu.open").on("click", 'li a', function () {
            _this.click();
        })
    }
    this.click = function () {
        _this.choose(this);
    }
    this.getValue = function ()// 获取行政区划的值
    {
        var id = this.getObj().find("li.list").attr("id");
        var value = this.getObj().find("select.selectpicker").val();
        var params = {};
        params[id] = value;
        return params;
    }
    this.setValue = function (result)// 设置下拉框选项内容
    {
        var data = result.data;
        if (result.state == "true") {
            data = JSON.parse(data);
            var select = this.getObj().find("select.selectpicker");
            select.empty();
            if (this.contentData["DEFAULT"] == "true") {
                var option = $("<option>");
                option.attr("value", "").html("不限");
                select.append(option);
            }
            for (var i in data) {
                var option = $("<option>");
                option.attr("value", data[i].ID).html(data[i].NAME);
                select.append(option);
            }
            /** 刷新下拉框的值 */
            select.selectpicker('val', '');
            select.selectpicker('refresh');
            select.selectpicker({
                size: 6
            });
            var _this = this;
            _this.getObj().find(".list").attr("state", "complete");
            _this.find("li a").first().trigger("click");
        }
    }
    this.querySQL = function (params)// 查询sql设置下拉框内容
    {
        var _this = this;
        var sql = params.sql;
        delete params.sql;

        queryBySql(sql, function (result) {
            return _this.setValue(result);
        }, params);
    }
    this.choose = function (obj)// 改变下拉框的状态
    {
        var _this = this;
        var relation = this.contentData["RELATION"];
        /** 判断是否在顶部显示 */
        if (this.contentData["IS_SHOW_TOP"] == "1") {
            var div = $("#chart_container").find(".page-search-top .place-div");
            div.html(text);
        }
        /** 判断是否存在级联关系进行下个下拉框的赋值 */
        if (relation) {
            var ins = $("#" + relation).parents(".form-widget-control-wapper");
            var param = _this.getValue();
            var params = contentDataAll[ins.attr("id")];
            params = $.extend(params, {}, param);
            if("select_xzqh"==params.type)
            {
                ins.select_xzqh("loadData", params, contentDataAll);
            }
            else if("select_jg"==params.type)
            {
                ins.select_jg("loadData", params, contentDataAll);
            }
            else
            {
                ins.select_common("loadData", params, contentDataAll);
            }
        }
    }
    this.loadData = function (param)// 加载下拉框内容
    {
        var _this = this;
        var params = {};
        params = $.extend(params, param);
        params["sql"] = contentData["SQL"];
        if (userInfo["WSJGLBDM"].indexOf("R") != -1) {
            this.querySQL(params);
        } else {
            _this.contentData.DEFAULT = "false";
            var res = {
                state: "true",
                data: JSON.stringify([{
                    ID: userInfo["JGDM"],
                    NAME: userInfo["JGMC"]
                }])
            };
            this.setValue(res);
        }
    }
    return this[action](contentData);
}

/** 图表视图 */
$.fn.chartView = function (action, params) {
    this.setValue = function (result) {
        var resToOptionIns = new resToOption();
        var opt = $(this).data("option");
        var type = $(this).attr("type");
        result["type"] = type;
        var _this_ = this;
        var view_common = function (result) {
            var option = resToOptionIns.getOption(result, opt);
            var ins = echarts.getInstanceByDom($(_this_).find(".echarts-div")[0]);
            delete option.tooltip.formatter;
            ins.setOption(option, true);
            ins.resize();
        }
        /** 散点图 */
        var view_scatter = function (result) {
            view_common(result);
        }
        /** 条形图 */
        var view_bar = function (result) {
            view_common(result);
        }
        /** 柱状图 */
        var view_column = function (result) {
            view_common(result);
        }
        /** 折线图 */
        var view_line = function (result) {
            view_common(result);
        }

        /** 仪表盘 */
        var view_gauge = function (result) {
            view_common(result);
        }
        /** 环形图 */
        var view_pie = function (result) {
            view_common(result);
        }
        /** 金字塔 */
        var view_pyramid = function (result) {
            view_common(result);
        }
        /** 雷达图 */
        var view_radar = function (result) {
            view_common(result);
        }
        /** 漏斗图 */
        var view_funnel = function (result) {
            view_common(result);
        }
        /** 多坐标轴图 */
        var view_axisLine = function (result) {
            view_common(result);
        }
        /** 多坐标系图 */
        var view_gridbar = function (result) {
            view_common(result);
        }
        /** 列表表格（类似top表） */
        var view_overviewtable = function (result) {
            view_toptable(result);
        }
        /** 报表 */
        var view_normaltable = function (result) {
            var option = resToOptionIns.getOption(result, opt);
            var ins = chartTable.getInstanceByDom($(_this_).find(".echarts-div")[0]);
            ins.setOption(option);
            ins.resize();
        }

        /** top表格 */
        var view_toptable = function (result) {
            var option = resToOptionIns.getOption(result, opt);
            var ins = chartTableTop.getInstanceByDom($(_this_).find(".echarts-div")[0]);
            ins.setOption(option);
            var total = result.rows;
            $(_this_).find(".h4-title .span-text").html("TOP" + total);
            ins.resize();
        }
        var view_datagrid = function (result) {
            var ins = $(_this_).find(".custom_datagrid");
            ins.datagrid('loadData', result.data);
            // ins.datagrid({data: result.data});

        }
        var view_treegrid = function (result) {
            var ins = $(_this_).find(".custom_treegrid");
            //特殊处理
            result.data.rows = JSON.parse(JSON.stringify(result.data.rows).replaceAll("PARENTID","_parentId"));
            ins.treegrid('loadData', result.data);

        }
        var func_name = "view_" + type;
        func_name = eval(func_name);
        func_name(result);
    }
    return this[action](params);
}

function getyyyyMMdd(d,sjwd) {
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();
    String(curr_month).length < 2 ? (curr_month = "0" + curr_month) : curr_month;
    String(curr_date).length < 2 ? (curr_date = "0" + curr_date) : curr_date;
    var yyyyMMdd = "";
    if("year"==sjwd){
        yyyyMMdd = curr_year;
    }else if("month"==sjwd){
        yyyyMMdd = curr_year + "-" + curr_month;
    }else{
        yyyyMMdd = curr_year + "-" + curr_month + "-" + curr_date;
    }
    return yyyyMMdd;
}

function layDate(now,defaultSjwd) {
    var newDate = getyyyyMMdd(now,defaultSjwd);
    var startDate = {
        elem: ".startDate",
        value: newDate
    };
    var endDate = {
        elem: ".endDate",
        value: newDate
    };
    if ("day" != defaultSjwd) {
        startDate = {
            elem: ".startDate",
            type: defaultSjwd,
            value: newDate
        };
        endDate = {
            elem: ".endDate",
            type: defaultSjwd,
            value: newDate
        };
    }
    //需预加载
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render(startDate);
        laydate.render(endDate);
    });
}
String.prototype.replaceAll = function(s1,s2){
    return this.replace(new RegExp(s1,"gm"),s2);
}